<?php
class Services_Ebay_Message_Send extends QDB_ActiveRecord_Abstract
{
	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => '',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
			    # '插件名' => array('选项' => 设置),
			),

			// 用什么数据表保存对象
			'table_name' => 'services_ebay_message_send',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *	array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
	
	static function create($send)
	{
		if ($send)
		{
			$insert = new Services_Ebay_Message_Send();
			$insert->services_ebay_message_id = $send['services_ebay_message_id'];
			$insert->shop_id = $send['shop_id'];
			$insert->shop_item_id = $send['shop_item_id'];
			$insert->sender = $send['sender'];
			$insert->recipient = $send['recipient'];
			$insert->send_user_id = CURRENT_USER_ID;
			$insert->send_time = CURRENT_DATETIME;
			$insert->send_flag = $send['send_flag'];
			$insert->body = $send['body'];
			$insert->save();
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '');
		}
	}
	
	static function addMemberMessageRTQ($message, $body, $picture, $send_id)
	{
		$token = Shop_API_Ebay::find('shop_id=?', $message['shop_id'])->asArray()->getOne();
		if ($token)
		{
			$header = array(
				'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
				'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
				'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
				'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
				'X-EBAY-API-SITEID:0',
				'X-EBAY-API-CALL-NAME:AddMemberMessageRTQ'
			);
			$xml ='<?xml version="1.0" encoding="utf-8"?>';
			$xml .='<AddMemberMessageRTQRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
			$xml .='  <RequesterCredentials>';
			$xml .='    <eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
			$xml .='  </RequesterCredentials>';
			$xml .='  <ItemID>' . $message['shop_item_id'] . '</ItemID>';
			$xml .='  <MemberMessage>';
			$xml .='    <Body>' . $body . '</Body>';
			$xml .='    <DisplayToPublic>false</DisplayToPublic>';
			$xml .='    <EmailCopyToSender>true</EmailCopyToSender>';
			if ($picture)
			{
				foreach ($picture as $p)
				{
					$xml .= '<MessageMedia>';
					$xml .=   '<MediaName>' . $p['name'] . '</MediaName>';
					$xml .=   '<MediaURL>' . $p['url'] . '</MediaURL>';
					$xml .= '</MessageMedia>';
				} 
			}
			$xml .='    <ParentMessageID>' . $message['external_message_id'] . '</ParentMessageID>';
			$xml .='    <RecipientID>' . $message['sender'] . '</RecipientID>';
			$xml .='  </MemberMessage>';
			$xml .='  <ErrorLanguage>en_US</ErrorLanguage>';
			$xml .='  <WarningLevel>High</WarningLevel>';
			$xml .='</AddMemberMessageRTQRequest>';
			$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'AddMemberMessageRTQ');
			if ($result['ack'] == SUCCESS)
			{
				$response = simplexml_load_string($result['data']);
				if ($response && $response->Ack == 'Success')
				{
					$send_time = date('Y-m-d H:i:s', strtotime((string)$response->Timestamp[0]));
					QDB::getConn()->execute('update services_ebay_message set replied=' . Q::ini('custom_flag/services_ebay_message_replied/replied/value') . ',response_time=\'' . $send_time . '\' where id=\'' . $message['id'] . '\'');
					QDB::getConn()->execute('update services_ebay_message_send set send_flag=' . Q::ini('custom_flag/services_ebay_message_send_send_flag/success/value') . ',send_time=\'' . $send_time . '\' where id=\'' . $send_id . '\'');
					return array('ack' => SUCCESS, 'message' => '');
				}
				else
				{
					return array('ack' => FAILURE, 'message' => isset($response->Errors[0]->ShortMessage[0]) ? (string)$response->Errors[0]->ShortMessage[0] : '');
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => $result['message']);
			}
		}
	}
	
	static function addMemberMessageAAQToPartner($message, $send_id)
	{
		
		$token = Shop_API_Ebay::find('shop_id=?', $message['shop_id'])->asArray()->getOne();
		if ($token)
		{
			$header = array(
				'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
				'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
				'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
				'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
				'X-EBAY-API-SITEID:0',
				'X-EBAY-API-CALL-NAME:AddMemberMessageAAQToPartner'
			);
			$xml = '<?xml version="1.0" encoding="utf-8"?>';
			$xml .='<AddMemberMessageAAQToPartnerRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
			$xml .=  '<RequesterCredentials>';
			$xml .=  '  <eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
			$xml .=  '</RequesterCredentials>';
			$xml .=  '<ItemID>' . $message['shop_item_id'] . '</ItemID>';
			$xml .=  '<MemberMessage>';
			$xml .=    '<QuestionType>General</QuestionType>';
			$xml .=    '<EmailCopyToSender>true</EmailCopyToSender>';
			$xml .=    '<RecipientID>' . $message['recipient'] . '</RecipientID>';
			$xml .=    '<Body>' . $message['body'] . '</Body>';
			if ($message['picture'])
			{
				foreach ($message['picture'] as $mp)
				{
					$xml .= '<MessageMedia>';
					$xml .=   '<MediaName>' . $mp['name'] . '</MediaName>';
					$xml .=   '<MediaURL>' . $mp['url'] . '</MediaURL>';
					$xml .= '</MessageMedia>';
				}
			}
			$xml .=  '</MemberMessage>';
			$xml .=  '<ErrorLanguage>en_US</ErrorLanguage>';
			$xml .=  '<WarningLevel>High</WarningLevel>';
			$xml .='</AddMemberMessageAAQToPartnerRequest>';
			$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'AddMemberMessageAAQToPartner', 1, true, $message['shop_item_id']);
			if ($result['ack'] == SUCCESS)
			{
				$response = simplexml_load_string($result['data']);
				if ($response && $response->Ack == 'Success')
				{
					$send_time = date('Y-m-d H:i:s', strtotime((string)$response->Timestamp[0]));
					QDB::getConn()->execute('update services_ebay_message_send set send_flag=' . Q::ini('custom_flag/services_ebay_message_send_send_flag/success/value') . ',send_time=\'' . $send_time . '\' where id=\'' . $send_id . '\'');
					return array('ack' => SUCCESS, 'message' => '');
				}
				else
				{
					return array('ack' => FAILURE, 'message' => isset($response->Errors[0]->ShortMessage[0]) ? (string)$response->Errors[0]->ShortMessage[0] : '');
				}
			}
		}
	}
	
	static function search($condition, $cp, $ps)
	{
		$columns = array(
			'services_ebay_message_send.*',
			'user.name as send_user_name'
		);
		$where = Services_Ebay_Message_Send::buildSearchWhere($condition);
		$select = Services_Ebay_message_Send::find($where)
			->joinLeft('services_ebay_message', '', 'services_ebay_message_send.services_ebay_message_id=services_ebay_message.id')
			->joinLeft('user', '', 'user.id=services_ebay_message_send.send_user_id')
			->setColumns($columns)->order('services_ebay_message_send.send_time desc');
		if ($cp == 0 && $ps == 0)
		{
			$pagination = array();
		}
		else
		{
			$select->limitPage($cp, $ps);
			$pagination = $select->getPagination();
		}
		$send = $select->asArray()->getAll();
		return array(
			'ack' => SUCCESS,
			'message' => '',
			'data' => $send,
			'pagination' => $pagination
		);
	}
	
	static function buildSearchWhere($condition)
	{
		$where = '1';
		if ( ! empty($condition['shop_user_mapping']))
		{
			$shop_id = Shop_User_Mapping::getShopIdByUserId();
			$where .= ' and services_ebay_message_send.shop_id in (\'' . implode('\',\'', $shop_id) . '\')';
		}
		if (isset($condition['shop_ids']))
		{
			$where .= ' and services_ebay_message_send.shop_id in(\'' . implode('\',\'', $condition['shop_ids']) . '\')';
		}
		if (! empty($condition['begin_send_time']))
		{
			$where .= ' and services_ebay_message_send.send_time>=\'' . $condition['begin_send_time'] . '\'';
		}
		if (! empty($condition['end_send_time']))
		{
			$where .= ' and services_ebay_message_send.send_time<=\'' . $condition['end_send_time'] . ' 23:59:59\'';
		}
		if (! empty($condition['recipient']))
		{
			$where .= ' and services_ebay_message_send.recipient=\'' . $condition['recipient'] . '\'';
		}
		if (isset($condition['send_flag']))
		{
			$send_flag_filter = '0';
			foreach (Q::ini('custom_flag/services_ebay_message_send_send_flag') as $sf)
			{
				if (isset($condition['send_flag'][$sf['value']]) && $condition['send_flag'][$sf['value']] == $sf['value'])
				{
					$send_flag_filter .= ' or services_ebay_message_send.send_flag=' . $sf['value'];
				}
			}
			$where .= ' and (' . $send_flag_filter . ')';
		}
		if (isset($condition['send_type']))
		{
			$send_type_filter = '0';
			if (in_array('contact', $_GET['send_type']))
			{
				$send_type_filter .= ' or services_ebay_message_send.services_ebay_message_id=\'\'';
			}
			if (in_array('response', $_GET['send_type']))
			{
				$send_type_filter .= ' or services_ebay_message_send.services_ebay_message_id!=\'\'';
			}
			$where .= ' and (' . $send_type_filter . ')';
		}
		return $where;
	}
}